package cmpe226.spring2011.project1;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;

public class ImportStocksApp {
    private static final int CHUNK_SIZE = 40;
    private Properties config = new Properties();

    /**
     * @param args
     */
    public static void main(String[] args) {
        ImportStocksApp app = new ImportStocksApp();
        app.loadProperties();
        
        long starttime = System.currentTimeMillis();
        app.importStocks(args[0]);
        long elapsed = System.currentTimeMillis() - starttime;
        
        System.out.println("Elapsed Time: " + (elapsed/1000F) + " seconds");
    }

    private void loadProperties() {
        InputStream in = ImportStocksApp.class.getClassLoader().getResourceAsStream("setup.properties");
        try {
            config.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void importStocks(String datadir) {
        String dbname = "localhost/" + config.getProperty("dbname");
        String user = config.getProperty("user");
        String pw = config.getProperty("pw");
        
        try {
            BigDAO db = new BigDAO(dbname, user, pw);
            
            File[] files = (new File(datadir)).listFiles();
            int index = 0;
            while (index < files.length) {
                List<File> chunk = new ArrayList<File>();
                for (int i = 0; i < CHUNK_SIZE; i++) {
                    if (index >= files.length)
                        break;
                    
                    chunk.add(files[index]);
                    index++;
                }
                
                Map<String, List<RecordDTO>> data = DataExtractor.getData(chunk);
                List<Symbol> symbols = DataMapper.transformToDomainObjects(data);
                db.save(symbols);
            }
            
            System.out.println("Stock symbols from " + datadir + " saved.");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
